package com.cskaoyan.service;

import com.cskaoyan.bean.bo.CategoryBO;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.po.CategoryPO;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author by WANGJun
 * @date 2022/6/5 15:15
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public TVO<CategoryListVOWithChild> listCategory(BaseParam baseParam) {
        List<CategoryPO> categoryPOS = categoryMapper.selectCategory(baseParam);
        Iterator<CategoryPO> iterator = categoryPOS.iterator();
        List<CategoryListVOWithChild> categoryListVOWithChildren = new ArrayList<>();
        while (iterator.hasNext()){
            CategoryPO categoryPO = iterator.next();
            CategoryListVOWithChild voWithChild = CategoryListVOWithChild.setCategoryListVO(categoryPO);
            Iterator<CategoryPO> childrenIterator = categoryMapper.selectCategoryByPid(categoryPO.getId()).iterator();
            List<CategoryListVO> categoryListVOS = new ArrayList<>();
            while (childrenIterator.hasNext()){
                CategoryPO next = childrenIterator.next();
                categoryListVOS.add(CategoryListVO.setCategoryListVO(next));
            }
            voWithChild.setChildren(categoryListVOS);
            categoryListVOWithChildren.add(voWithChild);
        }
        int total = categoryMapper.selectCategoryCount();
        TVO<CategoryListVOWithChild> categoryTVO = new TVO<>();
        categoryTVO.setPage(1);
        categoryTVO.setPages(1);
        categoryTVO.setLimit(total);
        categoryTVO.setTotal(total);
        categoryTVO.setList(categoryListVOWithChildren);
        return categoryTVO;
    }

    @Override
    public CategoryVO createCategory(CategoryBO categoryBO) {
        categoryMapper.addCategory(categoryBO);
        CategoryVO categoryVO = categoryMapper.selectCategoryById(categoryBO.getId());
        return categoryVO;
    }

    @Override
    public int updateCategory(CategoryBO categoryBO) {
        int updateCategory = categoryMapper.updateCategory(categoryBO);
        return updateCategory;
    }

    @Override
    public int deleteCategory(Integer id) {
        int deleteCategory = categoryMapper.deleteCategory(id);
        return deleteCategory;
    }

    @Override
    public TVO<CategoryL1VO> l1() {
        TVO<CategoryL1VO> tvo = new TVO<>();
        List<CategoryL1VO> categoryL1VOS = categoryMapper.selectCategoryLevel1();
        int total = categoryMapper.selectCategoryL1Count();
        tvo.setPage(1);
        tvo.setPages(1);
        tvo.setLimit(total);
        tvo.setTotal(total);
        tvo.setList(categoryL1VOS);
        return tvo;
    }
}
